from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from model.certificate import Certificate
from route.user_api import get_current_user
from schema.base_schema import BaseResponse
from schema.certificate_schema import CertificateCreate, CertificateUpdate, CertificateOut, CertificateApply
from services import certificate
import logging

logger = logging.getLogger("fast-run")

router = APIRouter(tags=["certificates"], dependencies=[Depends(get_current_user)])

@router.get("", response_model=list[CertificateOut])
def list_certificates(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return certificate.get_certificates(db, skip, limit)

@router.post("", response_model=CertificateOut)
def create_certificate(cert: CertificateCreate, db: Session = Depends(get_db)):
    return certificate.create_certificate(db, cert)

@router.put("/{cert_id}", response_model=CertificateOut)
def update_certificate(cert_id: int, cert: CertificateUpdate, db: Session = Depends(get_db)):
    updated = certificate.update_certificate(db, cert_id, cert)
    if not updated:
        raise HTTPException(status_code=404, detail="Certificate not found")
    return updated

@router.delete("/{cert_id}", response_model=CertificateOut)
def delete_certificate(cert_id: int, db: Session = Depends(get_db)):
    deleted = certificate.delete_certificate(db, cert_id)
    if not deleted:
        raise HTTPException(status_code=404, detail="Certificate not found")
    return deleted

# 可扩展：导出 fullchain / privkey
@router.get("/{cert_id}/download")
def download_certificate(cert_id: int, db: Session = Depends(get_db)):
    cert = certificate.get_certificate(db, cert_id)
    if not cert:
        raise HTTPException(status_code=404, detail="Certificate not found")
    return {
        "domain": cert.domain,
        "fullchain": cert.fullchain,
        "privkey": cert.privkey
    }

@router.post("/apply", response_model=BaseResponse)
def delete_certificate(cert_apply: CertificateApply,db: Session = Depends(get_db)):
    # 先检查数据库中是否已有该域名的证书
    existing_cert = db.query(Certificate).filter(Certificate.domain == cert_apply.domain).first()
    if existing_cert:
        raise HTTPException(status_code=400, detail="该域名已有证书，不能重复申请")
    if certificate.check_a_record(cert_apply.domain,cert_apply.host):
        logger.info("解析成功, 开始申请证书")
        cert = certificate.apply_certificate(cert_apply.domain,cert_apply.host)
        # 保存到数据库
        new_cert = Certificate(
            domain=cert_apply.domain,
            cert=getattr(cert, "cert", None),
            fullchain=cert['fullchain'],
            privkey=cert['privkey'],
            requested_at=datetime.now()  # 记录申请时间
        )
        db.add(new_cert)
        db.commit()
        db.refresh(new_cert)  # 可选，刷新获取最新状态

        return BaseResponse(status="success", message="证书申请并保存成功")
    else:
        return BaseResponse(status="error", message="dns解析错误")

